﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Songzeyu.Helper;
using Songzeyu.Pay;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Angelshaka_wxpay.Controllers.WxPay
{
    /// <summary>
    /// 微信支付通知_微信支付通过支付通知接口将用户支付成功消息通知给商户
    /// </summary>
    [Route("wxpay/[controller]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "微信支付")]
    public class NotifyController : ControllerBase
    {
        [HttpPost]
        [AllowAnonymous]
        public async Task<object> HttpPost()
        {
            try
            {
                string Timestamp = Request.Headers["Wechatpay-Timestamp"];
                string Nonce = Request.Headers["Wechatpay-Nonce"];
                string Signature = Request.Headers["Wechatpay-Signature"];
                string Serial = Request.Headers["Wechatpay-Serial"];
                StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8);
                string ciphertext = await reader.ReadLineAsync();
                reader.Close();

                var verify = await WeChatPay.Context.Verify(Timestamp, Nonce, ciphertext, Signature, Serial);
                NLogHelper.Info($"微信支付通知回调_验签:{verify}");
                if (!verify)
                {
                    NLogHelper.Error($"微信支付回调_验签失败：{Environment.NewLine}Timestamp：{Timestamp + Environment.NewLine}Nonce：{Nonce + Environment.NewLine}ciphertext：{ciphertext + Environment.NewLine}Signature：{Signature + Environment.NewLine}Serial：{Serial + Environment.NewLine}");
                    HttpContext.Response.StatusCode = 500;
                    return new { code = "FAIL", message = "失败" };
                }

                var plaintext = WeChatPay.Context.APIv3Decrypt(ciphertext);
                NLogHelper.Info($"微信支付通知回调_报文解密:{plaintext}");

                return new { code = 1, data = verify };
            }
            catch (Exception ex)
            {
                NLogHelper.Error($"NotifyController_HttpPost_错误：{ex.Message}");
                HttpContext.Response.StatusCode = 500;
                return new { code = "FAIL", message = "失败" };
            }
        }


    }
}
